import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Class to represent Chris Hansen's eyes
 */
public class ChrisEye  extends Actor implements Runnable
{  
    Chris c;  
    Simon simon;
    GreenfootImage original;
    // GreenfootImage current;
    retroWorld theWorld;
    private volatile Thread t;
    boolean alive;
    int halfWorld;
    
    /** Create a Chris Eye and link it to Chris
     * 
     */
    public ChrisEye(Chris c)
    {
      alive=true;
    
      original=new GreenfootImage("eye.png");
      retroWorld theWorld;
 
      this.c=c;       
    }

    public void run()
    {
        while(alive && simon!=null)
        {
            refresh();
            
                
            try {
                t.sleep(20);
            } catch (InterruptedException e) {}
        }
    }
    
    
    private void refresh(){
        int xSimon=simon.getX();       
        int x=getX();          
        int delta=(xSimon-x);
        boolean right=true;         
           
        if(delta<0){
            right=false;
            delta=(x-xSimon);
        }
        
        
        int rotation= delta*60/halfWorld;
         
        if(right)
           rotation=360-rotation;
                
        setImage(original); 
        setRotation(rotation);                
    }
    
    public void addedToWorld(World world)
    {
        theWorld = (retroWorld)world;
        halfWorld=theWorld.getWidth()/2;
        simon = theWorld.getSimon();
        t = new Thread(this);
        t.start();
    }
    
    public void removeFromWorld()
    {
         alive=false;
         t=null;
         theWorld.removeObject(this);
    }   
}
